package gw.com.android.presenter.http;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.interfaces.ReqCallBack;

/**
 * @author jett
 * @since 2017-11-23.
 */
public class FlashRequest {

    private static final int PAGE_SIZE = 20;

    private String cacheFileName = "_flash2.dat";
    private int currPage;
    private int count = -1;
    private DateFormat sourceFormat;
    private DateFormat dateFormat;
    private DateFormat timeFormat;

    public List<FlashData> fetchLocal() {
        String str = CacheUtils.readFile(cacheFileName);
        return parse(str, false);
    }

    public void call(ReqCallBack<List<FlashData>> callBack) {
        currPage = 1;
        count = -1;
        sendRequest(callBack);
    }

    private void sendRequest(final ReqCallBack<List<FlashData>> callBack) {
        String url = ConfigUtil.instance().getUrlPath("openApi");
        new Https(url)
                .addParam("service", "Advisory.quickList")
                .addParam("page", String.valueOf(currPage))
                .addParam("pageSize", String.valueOf(PAGE_SIZE))
                .addParam("utmTerminal", "app")//UMS接口，utmTerminal：终端类别
//                .addParam("companyId", ConfigUtil.instance().mConfigObject.optString(ConfigType.COMPANY_ID_TAG))//公司ID：FT 18
                .addParam("companyId", "2")//TODO 临时决定 快讯的公司id传2，后期可能会改，所以暂时写成2，读9999的快讯
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        List<FlashData> list = parse(result, true);
                        if (callBack != null) {
                            callBack.onReqSuccess(list);
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callBack != null) {
                            String msg = e == null ? "" : e.getMessage();
                            callBack.onReqFailed(msg);
                        }
                    }
                });
    }

    public void nextPage(ReqCallBack<List<FlashData>> callBack) {
        currPage++;
        sendRequest(callBack);
    }

    public boolean hasNextPage() {
        return count > currPage * PAGE_SIZE;
    }

    private List<FlashData> parse(String str, boolean cache) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson != null) {
                count = dataJson.optInt("count");
                JSONArray listArr = dataJson.optJSONArray("list");
                if (listArr != null && listArr.length() > 0) {
                    List<FlashData> datas = new ArrayList<>();
                    for (int i = 0; i < listArr.length(); i++) {
                        JSONObject json = listArr.optJSONObject(i);
                        if (json != null) {
                            FlashData data = new FlashData();
                            data.content = json.optString("title");
                            Date mDate = formatDate(json.optString("ctime"));
                            data.date = getDate(mDate);
                            data.time = getTime(mDate);
                            data.week = getWeek(mDate);
                            datas.add(data);
                        }
                    }
                    if (cache && currPage == 1) {
                        CacheUtils.writeFile(cacheFileName, str);
                    }
                    return datas;
                }
            }
        } catch (JSONException ignore) {
        }
        return null;
    }

    private Date formatDate(String time) {
        if (TextUtils.isEmpty(time)) {
            return new Date();
        }
        if (sourceFormat == null) {
            sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        }
        try {
            return sourceFormat.parse(time);
        } catch (ParseException e) {
            return new Date();
        }
    }

    private String getDate(Date date) {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        }
        return dateFormat.format(date);
    }

    private String getTime(Date date) {
        if (timeFormat == null) {
            timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        }
        return timeFormat.format(date);
    }

    private int getWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    public class FlashData {
        public String content;
        public String date;
        public String time;
        public int week;
    }

}
